package com.cloud.media.api.web;

import java.net.URLEncoder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.cloud.media.api.service.MediaStorageService;

@RestController
@RequestMapping("media/api/storage")
public class MediaStorageController {

	@Autowired
	private MediaStorageService mediaStorageService;

	@RequestMapping("upload")
	public void uplad(@RequestParam(value = "file", required = true)MultipartFile file, String path){
		mediaStorageService.upload(file, path);
	}
	
	@RequestMapping("download")
	public ResponseEntity<InputStreamResource> download(String path) throws Exception{
		HttpHeaders headers = new HttpHeaders();
		String fileName = path.substring(path.lastIndexOf("/") + 1, path.length());
		fileName = URLEncoder.encode(fileName, "utf-8");
		headers.add("Content-Disposition", "attachment;filename=\""+ fileName + "\"");
		if(fileName.toLowerCase().endsWith("mp4")){
			headers.add("Content-Type", "video/mpeg");
		}else{
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		}
		InputStreamResource inputStreamResource = new InputStreamResource(mediaStorageService.download(path));
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers,HttpStatus.OK);
	}
	
	@RequestMapping("delete")
	public void delete(String path){
		mediaStorageService.delete(path);
	}
}
